<template>
  <div class="space-y-6">
    <el-card class="shadow-sm">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-xl font-semibold text-gray-800">菜单管理</span>
          <el-button
            v-if="hasPermission('menu:create')"
            type="primary"
            @click="handleAdd"
            class="px-4 py-2"
          >
            <el-icon class="mr-1">
              <Plus />
            </el-icon>新增菜单
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="mb-4">
        <el-form-item label="菜单名称">
          <el-input v-model="searchForm.name" placeholder="请输入菜单名称" class="w-48" />
        </el-form-item>
        <el-form-item label="菜单类型">
          <el-select v-model="searchForm.type" placeholder="请选择菜单类型" clearable class="w-48">
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch(searchForm)">搜索</el-button>
          <el-button @click="handleReset({ name: '', type: '' })">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 菜单树形表格 -->
      <div class="overflow-x-auto">
        <el-table
          :data="menuList"
          v-loading="loading"
          border
          style="width: 100%"
          class="text-sm compact-table"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :default-expand-all="!searchForm.name && !searchForm.type"
          :row-style="{ height: '40px' }"
          :cell-style="{ padding: '4px 0' }"
          :header-cell-style="{ padding: '8px 0', height: '45px' }"
        >
          <el-table-column prop="name" label="菜单名称" min-width="200">
            <template #default="{ row }">
              <span class>
                <el-icon v-if="row.icon" class="mr-1">
                  <component :is="row.icon" />
                </el-icon>
                <span class="truncate">{{ row.name }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="icon" label="图标" width="100">
            <template #default="{ row }">
              <el-icon v-if="row.icon">
                <component :is="row.icon" />
              </el-icon>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="80">
            <template #default="{ row }">
              <el-tag
                :type="getMenuTypeTag(row.type)"
                class="text-xs px-2 py-1"
              >{{ getMenuTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="路由路径" min-width="180" />
          <el-table-column prop="component" label="组件路径" min-width="180" />
          <el-table-column prop="permission" label="权限标识" min-width="150" />
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column prop="visible" label="可见" width="80">
            <template #default="{ row }">
              <DictTag
                dict-type="sys_visible"
                :value="row.visible"
                size="small"
                custom-class="text-xs px-2 py-1"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="flex space-x-1">
                <el-button
                  v-if="hasPermission('menu:create')"
                  type="primary"
                  size="small"
                  @click="handleAddChild(row)"
                  class="px-2 py-1 text-xs"
                >
                  <el-icon class="mr-1 text-xs">
                    <Plus />
                  </el-icon>新增
                </el-button>
                <el-button
                  v-if="hasPermission('menu:update')"
                  type="warning"
                  size="small"
                  @click="handleEdit(row)"
                  class="px-2 py-1 text-xs"
                >
                  <el-icon class="mr-1 text-xs">
                    <Edit />
                  </el-icon>编辑
                </el-button>
                <el-dropdown @command="handleCommand($event, row)">
                  <el-button size="small" class="px-2 py-1 text-xs">
                    <el-icon class="text-xs">
                      <More />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-if="hasPermission('menu:update')"
                        command="toggleStatus"
                      >{{ row.status ? '禁用' : '启用' }}</el-dropdown-item>
                      <el-dropdown-item
                        v-if="hasPermission('menu:update')"
                        command="toggleVisible"
                      >{{ row.visible ? '隐藏' : '显示' }}</el-dropdown-item>
                      <el-dropdown-item
                        v-if="hasPermission('menu:delete')"
                        command="delete"
                        divided
                        class="text-red-600"
                      >删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 菜单表单对话框 -->
    <MenuFormDialog
      v-model="dialogVisible"
      :menu-data="currentMenu"
      :parent-menus="parentMenus"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getMenuList,
  getMenuTree,
  deleteMenu,
  updateMenuStatus,
  updateMenuVisible,
} from "@/api/menu";
import MenuFormDialog from "@/components/MenuFormDialog.vue";
import DictTag from "@/components/DictTag.vue";
import { Plus, Edit, More } from "@element-plus/icons-vue";
import { useAuthStore } from "@/stores/auth";

const loading = ref(false);
const menuList = ref([]);
const dialogVisible = ref(false);
const currentMenu = ref(null);

const authStore = useAuthStore();
const hasPermission = (permission) => {
  return authStore.hasPermission(permission);
};

const searchForm = reactive({
  name: "",
  type: "",
});

// 父级菜单列表（用于表单选择）
const parentMenus = computed(() => {
  const flattenMenus = (menus) => {
    // 确保menus是数组
    if (!Array.isArray(menus)) {
      return [];
    }

    const result = [];
    menus.forEach((menu) => {
      if (menu && typeof menu === "object") {
        result.push({
          id: menu.id,
          name: menu.name,
          type: menu.type,
        });
        // 只有在树形数据结构中才处理children
        if (
          menu.children &&
          Array.isArray(menu.children) &&
          menu.children.length > 0
        ) {
          result.push(...flattenMenus(menu.children));
        }
      }
    });
    return result;
  };

  return flattenMenus(menuList.value);
});

const loadMenus = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
    };

    // 判断是否有筛选条件
    const hasFilter = params.name || params.type;

    let data;
    if (hasFilter) {
      // 有筛选条件时使用平铺数据
      const res = await getMenuList(params);
      data = res.list;
    } else {
      // 无筛选条件时使用树形数据
      data = await getMenuTree(params);
    }

    menuList.value = data || [];
  } catch (error) {
    ElMessage.error("获取菜单列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = (params) => {
  Object.assign(searchForm, params);
  loadMenus();
};

const handleReset = (params) => {
  Object.assign(searchForm, params);
  loadMenus();
};

const handleAdd = () => {
  currentMenu.value = null;
  dialogVisible.value = true;
};

const handleAddChild = (row) => {
  currentMenu.value = {
    parentId: row.id,
    parentName: row.name,
  };
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  currentMenu.value = { ...row };
  dialogVisible.value = true;
};

const handleCommand = async (command, row) => {
  switch (command) {
    case "toggleStatus":
      await handleToggleStatus(row);
      break;
    case "toggleVisible":
      await handleToggleVisible(row);
      break;
    case "delete":
      await handleDelete(row);
      break;
  }
};

const handleToggleStatus = async (row) => {
  try {
    await updateMenuStatus(row.id, !row.status);
    ElMessage.success(`${row.status ? "禁用" : "启用"}成功`);
    loadMenus();
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

const handleToggleVisible = async (row) => {
  try {
    await updateMenuVisible(row.id, !row.visible);
    ElMessage.success(`${row.visible ? "隐藏" : "显示"}成功`);
    loadMenus();
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${row.name}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await deleteMenu(row.id);
    ElMessage.success("删除成功");
    loadMenus();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleSuccess = () => {
  loadMenus();
};

const getMenuTypeText = (type) => {
  const types = {
    1: "目录",
    2: "菜单",
    3: "按钮",
  };
  return types[type] || "未知";
};

const getMenuTypeTag = (type) => {
  const tags = {
    1: "primary", // 目录类型使用主要样式
    2: "success", // 菜单类型使用成功样式
    3: "info", // 按钮类型使用信息样式
  };
  // 确保返回有效的Element Plus tag类型
  return tags[type] || "primary"; // 默认返回primary，确保Element Plus使用有效样式
};

onMounted(() => {
  loadMenus();
});
</script>

<style scoped>
.compact-table {
  --el-table-header-padding: 8px 0;
  --el-table-cell-padding: 4px 0;
}

.compact-table :deep(.el-table__row) {
  height: 40px;
}

.compact-table :deep(.el-table__header) {
  height: 45px;
}

.compact-table :deep(.el-table__cell) {
  padding: 4px 0;
}

.compact-table :deep(.el-table__header-cell) {
  padding: 8px 0;
}

.compact-table :deep(.el-button--small) {
  padding: 4px 8px;
  font-size: 12px;
}

.compact-table :deep(.el-tag) {
  height: 24px;
  line-height: 22px;
  padding: 0 6px;
  font-size: 12px;
}

.compact-table :deep(.el-table__expand-icon) {
  height: 20px;
  line-height: 20px;
  width: 20px;
}

.compact-table :deep(.el-table__indent) {
  height: 20px;
}

.compact-table :deep(.el-table__expand-icon) .el-icon {
  font-size: 14px;
}
</style>